package com.sh.aspects;

import com.sh.bean.Resfood;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Map;

import static com.fasterxml.jackson.databind.type.LogicalType.Map;

/**
 * 统计菜品详情查看次数 aop方案
 */
@Aspect
@Component
@Order(10)
@Slf4j
public class DetailCountAspect {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Pointcut("execution(* com.sh.web.controller.ResfoodController.findById(..))")
    private void deposite(){
    }

    @AfterReturning(pointcut = "execution(* com.sh.web.controller.ResfoodController.findById(..))",
            returning = "resultMap")
    public void afterFindByIdMethod(JoinPoint joinPoint, java.util.Map<String, Object> resultMap) {
        // 在这里可以对返回的 map 进行处理
        System.out.println("返回的 map：" + resultMap);
        Resfood bean = (Resfood) resultMap.get("obj");
        int fid = Integer.parseInt(joinPoint.getArgs()[0].toString());
        Long increment = redisTemplate.opsForValue().increment("detail_count:" + fid);
        // resultMap.put("detail_count", increment);
        bean.setDetailCount(increment);
    }

    @AfterReturning("deposite()")  // 后置通知
    public void recordSearch(JoinPoint joinPoint){
        int fid = Integer.parseInt(joinPoint.getArgs()[0].toString());
        Long increment = redisTemplate.opsForValue().increment("detail_count:" + fid);
    }


}
